<template>
  <div class="comments-management">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <div class="header-left">
        <h2>评论管理</h2>
        <p>管理系统中的所有用户评论</p>
      </div>
      <div class="header-right">
        <el-button type="danger" @click="batchDelete" :disabled="selectedComments.length === 0">
          批量删除 ({{ selectedComments.length }})
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选栏 -->
    <div class="search-bar">
      <div class="search-left">
        <el-input
          v-model="searchQuery"
          placeholder="搜索评论内容、用户名、资源标题..."
          prefix-icon="Search"
          style="width: 400px;"
          @input="handleSearch"
          clearable
        />
      </div>
      <div class="search-right">
        <el-button icon="Refresh" @click="refreshData">刷新</el-button>
      </div>
    </div>

    <!-- 评论表格 -->
    <div class="table-container">
      <el-table 
        :data="comments"
        v-loading="loading"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :table-layout="'fixed'"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        
        <el-table-column prop="id" label="ID" width="80" sortable></el-table-column>
        
        <el-table-column label="用户信息" width="150">
          <template #default="{ row }">
            <div class="user-info" v-if="row">
              <div class="user-avatar">
                <span>👤</span>
              </div>
              <div class="user-details">
                <div class="username">{{ row.username || '未知用户' }}</div>
                <div class="user-id">ID: {{ row.userId }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="评论内容" min-width="300">
          <template #default="{ row }">
            <div class="comment-content" v-if="row">
              <p class="content-text">{{ row.content }}</p>
              <div class="comment-meta">
                <span class="resource-title">资源: {{ row.resourceTitle || '未知资源' }}</span>
                <el-rate 
                  v-if="row.rating" 
                  :value="row.rating" 
                  disabled 
                  size="small"
                  class="rating"
                />
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="createdAt" label="发表时间" width="160" sortable>
          <template #default="{ row }">
            <span v-if="row">{{ formatDate(row.createdAt) }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="updatedAt" label="更新时间" width="160" sortable>
          <template #default="{ row }">
            <span v-if="row">{{ formatDate(row.updatedAt) }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons" v-if="row">
              <el-button 
                link 
                type="danger" 
                size="small" 
                @click="deleteComment(row)"
                icon="Delete"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalComments"
      />
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Delete } from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  name: 'Comments',
  components: {
    Search,
    Refresh,
    Delete
  },
  setup() {
    // 响应式数据
    const comments = ref([])
    const loading = ref(false)
    const selectedComments = ref([])
    const searchQuery = ref('')
    const currentPage = ref(1)
    const pageSize = ref(20)
    const totalComments = ref(0)
    
    // 获取评论列表
    const loadComments = async () => {
      loading.value = true
      try {
        const response = await axios.get('/api/admin/comments', {
          params: {
            current: currentPage.value,
            size: pageSize.value,
            keyword: searchQuery.value
          },
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token') || 'mock-jwt-token-1'}`
          }
        })
        
        if (response.data && response.data.code === 200) {
          comments.value = response.data.data.records || []
          totalComments.value = response.data.data.total || 0
        } else {
          throw new Error(response.data?.message || '获取评论数据失败')
        }
      } catch (error) {
        console.error('加载评论数据失败:', error)
        ElMessage.error('加载评论数据失败: ' + (error.response?.data?.message || error.message))
        
        // 清空数据
        comments.value = []
        totalComments.value = 0
      } finally {
        loading.value = false
      }
    }
    
    const handleSearch = () => {
      currentPage.value = 1
      loadComments()
    }
    
    const refreshData = () => {
      loadComments()
    }
    
    const handleSelectionChange = (selection) => {
      selectedComments.value = selection
    }
    
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
      loadComments()
    }
    
    const handleCurrentChange = (page) => {
      currentPage.value = page
      loadComments()
    }
    
    const formatDate = (dateString) => {
      if (!dateString) return '-'
      const date = new Date(dateString)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      
      // 如果是今年，只显示月日和时间
      const currentYear = new Date().getFullYear()
      if (year === currentYear) {
        return `${month}-${day} ${hours}:${minutes}`
      } else {
        return `${year}-${month}-${day} ${hours}:${minutes}`
      }
    }
    
    const deleteComment = async (comment) => {
      try {
        await ElMessageBox.confirm(`确定要删除这条评论吗？此操作不可恢复！`, '删除确认', {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'error'
        })
        
        const response = await axios.delete(`/api/comments/${comment.id}`, {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token') || 'mock-jwt-token-1'}`
          }
        })
        
        if (response.data && response.data.code === 200) {
          ElMessage.success('评论删除成功')
          await loadComments()
        } else {
          ElMessage.error(response.data?.message || '评论删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除评论失败:', error)
          ElMessage.error('评论删除失败: ' + (error.response?.data?.message || error.message))
        }
      }
    }
    
    const batchDelete = async () => {
      if (selectedComments.value.length === 0) {
        ElMessage.warning('请先选择要删除的评论')
        return
      }
      
      try {
        await ElMessageBox.confirm(`确定要删除选中的 ${selectedComments.value.length} 条评论吗？此操作不可恢复！`, '批量删除确认', {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'error'
        })
        
        const commentIds = selectedComments.value.map(comment => comment.id)
        
        const response = await axios.delete('/api/admin/comments/batch', {
          data: { commentIds },
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token') || 'mock-jwt-token-1'}`
          }
        })
        
        if (response.data && response.data.code === 200) {
          ElMessage.success('批量删除成功')
          selectedComments.value = []
          await loadComments()
        } else {
          ElMessage.error(response.data?.message || '批量删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error)
          ElMessage.error('批量删除失败: ' + (error.response?.data?.message || error.message))
        }
      }
    }

    // 组件挂载时获取数据
    onMounted(() => {
      loadComments()
    })

    return {
      comments,
      loading,
      selectedComments,
      searchQuery,
      currentPage,
      pageSize,
      totalComments,
      loadComments,
      handleSearch,
      refreshData,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      formatDate,
      deleteComment,
      batchDelete
    }
  }
}
</script>

<style scoped>
.comments-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header-left h2 {
  margin: 0 0 5px 0;
  color: #333;
}

.header-left p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.header-right {
  display: flex;
  align-items: center;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.search-left {
  display: flex;
  gap: 10px;
  align-items: center;
}

.table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  overflow-x: auto;
}

.el-table {
  min-width: 1000px;
  border-radius: 0;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: white;
  flex-shrink: 0;
}

.user-details {
  flex: 1;
  min-width: 0;
}

.username {
  font-weight: 600;
  color: #333;
  font-size: 13px;
  margin-bottom: 1px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.user-id {
  color: #999;
  font-size: 11px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.comment-content {
  padding: 8px 0;
}

.content-text {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 14px;
  line-height: 1.4;
  word-break: break-word;
  max-height: 60px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.comment-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.resource-title {
  color: #666;
  font-size: 12px;
  background: #f5f5f5;
  padding: 2px 6px;
  border-radius: 3px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 150px;
}

.rating {
  margin: 0;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

.action-buttons .el-button {
  padding: 4px 8px;
  font-size: 12px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .comments-management {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .search-bar {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .search-left {
    flex-direction: column;
    align-items: stretch;
  }
  
  .el-input {
    width: 100% !important;
  }
}
</style> 